import MsgAdapt from "../../../gamenet/MsgAdapt";

export class BaseProtocolStruct {
    static className: string = `BaseProtocolStruct`;
    msgType: number = 0;
    status: number = -1;
    decodeCallBack: (protocol: BaseProtocolStruct) => void;
    init(){}

    encode(...arg: any){}
    decode(){}
    send(){
        MsgAdapt.send();
    }
    encodeAndSend(): Promise<BaseProtocolStruct>{
        return new Promise((resolve, reject) => {
            this.encode();
            this.send();
            this.decodeCallBack = resolve;
        });
    }
}

export class ProtocolPool {
    private static _instance: ProtocolPool = null;
    protocolList = {};
    protocolListByType: {[msgType: number]: BaseProtocolStruct} = {};

    static get instance(){
        if(!this._instance){
            this._instance = new ProtocolPool();
        }
        return this._instance;
    }

    onDestory(){
        this.protocolList = {};
        this.protocolListByType = {};
    }

    rigister(protocol: typeof BaseProtocolStruct){
        if(!protocol.className){
            console.error(`[BaseProtocol] --> 协议注册失败, 该协议缺少类静态成员 className`);
            return;
        }
        let regProtocol = new protocol();
        if(this.protocolListByType[regProtocol.msgType]){
            console.error(`协议重复注册 class:`, protocol.name, "msgType:",regProtocol.msgType);
            return -1;
        }
        regProtocol.init();
        console.log(`[BaseProtocol] --> 协议注册`, protocol.className, regProtocol.msgType);

        this.protocolList[protocol.className] = regProtocol;
        this.protocolListByType[regProtocol.msgType] = regProtocol;
        MsgAdapt.rigisterHandlers(regProtocol.msgType);
        return regProtocol.msgType;
    }

    getProtocol<T extends BaseProtocolStruct>(protocol: {prototype: T, className: string}): T {
        return this.protocolList[protocol.className];
    }

    getProtocolByType(msgType: number) {
        return this.protocolListByType[msgType];
    }
}
